#pragma once
#include <iostream>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cstring>
#include <unistd.h>

static int g_back = 20;

class Sock
{
public:
    Sock()
    {
    }

    int Socket() // 创建套接字
    {
        int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_sock < 0)
        {
            return -1;
        }

        return listen_sock;
    }

    bool Bind(int listen_sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        struct sockaddr_in server_addr;
        memset(&server_addr, 0, sizeof(server_addr));

        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = inet_addr(ip.c_str());
        server_addr.sin_port = htons(port);

        if (bind(listen_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
        {
            return false;
        }

        return true;
    }

    bool Listen(int listen_sock)
    {
        int sockId = listen(listen_sock, g_back);
        if (sockId < 0)
        {
            return false;
        }

        return true;
    }

    int Accept(int sockId)
    {
        return accept(sockId, nullptr, nullptr);
    }

    bool Connect(int sockId, uint16_t port, std::string ip)
    {
        struct sockaddr_in server_addr;
        memset(&server_addr, 0, sizeof(server_addr));

        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = inet_addr(ip.c_str());
        server_addr.sin_port = htons(port);

        return connect(sockId, (struct sockaddr *)&server_addr, sizeof(server_addr)) != -1;
    }

    ~Sock()
    {
    }
};